import path from 'path';
import fs from 'fs';

// 缓存敏感词汇列表
let sensitiveWordsCache: string[] | null = null;

// 加载敏感词汇
function loadSensitiveWords(): string[] {
  if (sensitiveWordsCache !== null) {
    return sensitiveWordsCache;
  }
  
  try {
    const sensitiveWordsPath = path.join(process.cwd(), 'public', 'SensitiveLexicon.json');
    const sensitiveData = JSON.parse(fs.readFileSync(sensitiveWordsPath, 'utf8'));
    sensitiveWordsCache = [...sensitiveData.words, ...(sensitiveData.en_words || [])];
    return sensitiveWordsCache;
  } catch (error) {
    console.error('读取敏感词汇文件失败:', error);
    sensitiveWordsCache = [];
    return sensitiveWordsCache;
  }
}

// 敏感词汇检查函数
export function checkSensitiveWords(text: string): { hasSensitive: boolean; sensitiveWords: string[] } {
  const sensitiveWords = loadSensitiveWords();
  
  if (sensitiveWords.length === 0 || !text || typeof text !== 'string') {
    return { hasSensitive: false, sensitiveWords: [] };
  }
  
  const foundSensitiveWords: string[] = [];
  
  // 按逗号分割文本，去除空格和空字符串
  const textTokens = text.split(',').map(token => token.trim()).filter(token => token.length > 0);
  
  // 检查每个分割后的子字符串是否与敏感词完全匹配（区分大小写）
  for (const token of textTokens) {
    for (const sensitiveWord of sensitiveWords) {
      // 完全匹配（区分大小写）
      if (token === sensitiveWord) {
        if (!foundSensitiveWords.includes(sensitiveWord)) {
          foundSensitiveWords.push(sensitiveWord);
        }
      }
    }
  }
  
  return {
    hasSensitive: foundSensitiveWords.length > 0,
    sensitiveWords: foundSensitiveWords
  };
}

// 检查prompt和negative_prompt的敏感词
export function checkPromptSensitiveWords(prompt: string, negativePrompt: string) {
  const promptCheck = checkSensitiveWords(prompt);
  const negativePromptCheck = checkSensitiveWords(negativePrompt);
  
  if (promptCheck.hasSensitive || negativePromptCheck.hasSensitive) {
    const allSensitiveWords = [...promptCheck.sensitiveWords, ...negativePromptCheck.sensitiveWords];
    return {
      hasSensitive: true,
      sensitiveWords: allSensitiveWords,
      error: {
        error: '内容包含敏感词汇，请修改后重试',
        detail: `检测到敏感词汇: ${allSensitiveWords.join(', ')}`,
        sensitiveWords: allSensitiveWords
      }
    };
  }
  
  return {
    hasSensitive: false,
    sensitiveWords: [],
    error: null
  };
}